﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Users;

namespace CK.Framework.HttpApi.Host
{
    public static class ServiceCollectionCurrentUser
    {
        public static void AddCurrentInfo(this IServiceCollection services)
        {
            services.AddTransient(typeof(CK.Sprite.ThirdContract.ICurrentUser), typeof(AbpCurrentUser));
            services.AddTransient(typeof(CK.Sprite.ThirdContract.ICurrentTenant), typeof(AbpCurrentTenant));
        }
    }

    /// <summary>
    /// 当前租户信息
    /// </summary>
    public class AbpCurrentUser : CK.Sprite.ThirdContract.ICurrentUser
    {
        private readonly Volo.Abp.Users.ICurrentUser _currentUser;
        public AbpCurrentUser(Volo.Abp.Users.ICurrentUser currentUser)
        {
            _currentUser = currentUser;
        }

        public string UserId
        {
            get
            {
                return _currentUser.Id.HasValue ? _currentUser.Id.ToString() : "";
            }
        }

        public string UserName
        {
            get
            {
                return _currentUser.UserName;
            }
        }

        public string DeptId
        {
            get
            {
                return (_currentUser.FindClaimValue<int>("dept_id")).ToString();
            }
        }

        public string Name
        {
            get
            {
                return _currentUser.FindClaimValue("user_name");
            }
        }

        public string[] Roles
        {
            get
            {
                return _currentUser.Roles;
            }
        }
    }

    /// <summary>
    /// 当前租户信息
    /// </summary>
    public class AbpCurrentTenant : CK.Sprite.ThirdContract.ICurrentTenant
    {
        private readonly Volo.Abp.MultiTenancy.ICurrentTenant _currentTenant;
        public AbpCurrentTenant(Volo.Abp.MultiTenancy.ICurrentTenant currentTenant)
        {
            _currentTenant = currentTenant;
        }

        public string TenantCode
        {
            get
            {
                return _currentTenant.Id.HasValue ? _currentTenant.Id.ToString() : "Default";
            }
        }

        public string Name
        {
            get
            {
                return _currentTenant.Name;
            }
        }
    }
}
